import loggers
import re
import sys
import os
from ConfigParser import ConfigParser

logger = loggers.loggers('spam-filter', 'spam-filter.log', 'INFO', True)

PLUGIN_DIR = os.path.expanduser('~/.sms-middleware/plugins/spam_filter')
FILENAME = 'config.cfg'
FILE_PATH = os.path.join(PLUGIN_DIR, FILENAME)

config = ConfigParser()

try:
    config.readfp(open(FILE_PATH))
except Exception, why:
    print why
    logger.warning('No configuration file=%s, creating one' % (FILENAME))
    try:
        os.makedirs(PLUGIN_DIR)
    except:
        pass
    f = open(FILE_PATH, 'w')
    f.close()
    config.readfp(open(FILE_PATH))

if not config.has_section('sim'):
    config.add_section('sim')
    config.write(open(FILE_PATH, 'w'))
if not config.has_section('text'):
    config.add_section('text')
    config.write(open(FILE_PATH, 'w'))

    
sim_r = [y for x,y in config.items('sim')]
text_r = [y for x,y in config.items('text')]
sim_c = [re.compile(entry) for entry in sim_r] 
text_c = [re.compile(entry) for entry in text_r]

def spam_helper(sim_number, text):
    
    for sim_re in sim_c:
        match_obj = sim_re.search(sim_number)
        if match_obj:
            logger.info("SIM matched re=%s sim=%s" % (match_obj.re.pattern, sim_number))
            return True

    for text_re in text_c:
        match_obj = text_re.search(text)
        if match_obj:
            logger.info("TEXT matched re=%s text=%s" % (match_obj.re.pattern, text))
            return True
        
    return False
    

def plugin_spam_filter(index, status, sim_number, text, interfaces):
    
    if spam_helper(sim_number, text) == True:
        logger.info('SPAM detected!, SMS index=%s is a spam' % (index))
        if interfaces.has_key('org.freesmartphone.GSM.SIM'):
            interfaces['org.freesmartphone.GSM.SIM'].DeleteMessage(
                index,
                reply_handler=lambda:logger.info('SMS index=%s removed' % (index)),
                error_handler=lambda x:logger.error('Could not remove SMS index=%s' % (index))
            )
    else:
        logger.info('SMS index=%s is NOT spam' % (index))
        
    